/**
 * 
 */
package com.pos.toolbox.file;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @description:文件管理
 * @author cai
 * @time:2014年12月16日下午5:05:19
 */
public class FilesManager {
	/**
	 * 图片下载文件夹名称
	 */
	public static final String imageFileName = "imageFile";
	/**
	 * 用户登录后对象存储名称
	 */
	public static final String User = "user";


	/**
	 * 创建图片目录文件夹
	 */
	public static void openFile(Context context) {
		File temp = getDownImageFolder(context);
		if (!temp.exists()) {
			temp.mkdir();
		}

	}

	/**
	 * 获取子文件夹file
	 */
	public static File getChildImageFolder(Context context, String childName) {
		return new File(Environment.getExternalStorageDirectory().getPath() + File.separator + imageFileName
				+ File.separator + childName);
	}

	/**
	 * 获取子文件夹file name
	 */
	public static String getChildImageFolderName(Context context, String childName) {
		return Environment.getExternalStorageDirectory().getPath() + File.separator + imageFileName + File.separator
				+ childName;
	}

	/**
	 * 获取下载图片存放路径文件夹file
	 */
	public static File getDownImageFolder(Context context) {
		return new File(getDownLoadImageFolderName(context));
	}

	/**
	 * 获取下载图片文件夹存放路径
	 */
	public static String getDownLoadImageFolderName(Context context) {
		// return context.getFilesDir().getAbsolutePath() + File.separator +
		// imageFileName;
		return Environment.getExternalStorageDirectory().getPath() + File.separator + imageFileName;
	}

	/**
	 * 保存图片文件
	 * 
	 * @param bitmap
	 *            即将保存为文件的bitmap
	 * @param fileName
	 *            文件名
	 */
	public static void saveImageFile(Context context, Bitmap bitmap, String path) {
		File jpgFile = new File(path);
		try {
			jpgFile.createNewFile();
			FileOutputStream outputStream = new FileOutputStream(jpgFile);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 70, outputStream);
			IOUtil.closeStream(outputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 去黑色背景保存图片文件
	 * 
	 * @param bitmap
	 *            即将保存为文件的bitmap
	 * @param fileName
	 *            文件名
	 */
	public static void savePngImageFile(Context context, Bitmap bitmap, String path) {
		File jpgFile = new File(path);
		try {
			jpgFile.createNewFile();
			FileOutputStream outputStream = new FileOutputStream(jpgFile);
			bitmap.compress(Bitmap.CompressFormat.PNG, 70, outputStream);
			IOUtil.closeStream(outputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取图片路径
	 * 
	 * @param fileName
	 *            图片文件名称
	 */
	public static String getImageFilePath(Context context, String fileName) {
		return getDownLoadImageFolderName(context) + File.separator + fileName;
	}

	/**
	 * 获取下载图片本地硬缓存地址全路径
	 * 
	 * @param url
	 *            图片url
	 */
	public static String getDownLoadImageDir(Context context, String url) {
		int index = url.lastIndexOf("/");
		return getImageFilePath(context, url.substring(index + 1, url.length()));

	}

	public static String getSystemPhotoPath() {
		return Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera";
	}

	/**
	 * 加载Assert文本文件，转换成String类型
	 * 
	 * @param context
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public static String loadAssetsText(Context context, String fileName) throws IOException {
		InputStream inputStream = context.getAssets().open(fileName, Context.MODE_PRIVATE);
		ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
		byte[] bytes = new byte[4096];
		int len = 0;
		while ((len = inputStream.read(bytes)) > 0) {
			byteStream.write(bytes, 0, len);
		}

		return new String(byteStream.toByteArray(), "UTF-8");
	}

	private static boolean isExistDataCache(Context context, String cachefile) {
		boolean exist = false;
		File data = context.getFileStreamPath(cachefile);
		if (data.exists())
			exist = true;
		return exist;
	}

	/**
	 * 保存对象
	 * 
	 * @param ser
	 * @param file
	 * @throws IOException
	 */
	public static boolean saveObject(Context context, Serializable ser, String file) {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			fos = context.openFileOutput(file, Context.MODE_PRIVATE);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(ser);
			oos.flush();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				oos.close();
			} catch (Exception e) {
			}
			try {
				fos.close();
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 读取对象
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static Serializable readObject(Context context, String file) {
		if (!isExistDataCache(context, file))
			return null;
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = context.openFileInput(file);
			ois = new ObjectInputStream(fis);
			return (Serializable) ois.readObject();
		} catch (FileNotFoundException e) {
		} catch (Exception e) {
			e.printStackTrace();
			// 反序列化失败 - 删除缓存文件
			if (e instanceof InvalidClassException) {
				File data = context.getFileStreamPath(file);
				data.delete();
			}
		} finally {
			try {
				ois.close();
			} catch (Exception e) {
			}
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		return null;
	}

}
